﻿using Springwater.Business.Enums;
using Springwater.Business.ViewModels;
using Springwater.DataAccessLayer.Model;
using Springwater.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Springwater.Web.Controllers
{
    public class BorvizController : BaseController
    {
        public ActionResult Index(int id)
        {
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(id);

            if (borviz != null)
            {
                return View(new BorvizModel(borviz));
            }
            else
            {
                return View("NotFound");
            }
        }

        #region Edit

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult Edit(int id)
        {
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(id);

            if (borviz != null)
            {
                var model = new BorvizEditModel(borviz);
                model.Init(this.UnitOfWork);

                return View(model);
            }
            else
            {
                return View("NotFound");
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult Edit(BorvizEditModel model)
        {
            model.Validate(this.ModelState, this.UnitOfWork);

            if (ModelState.IsValid)
            {
                var borviz = this.UnitOfWork.BorvizRepository.GetByID(model.Id);

                model.Leiras = HttpUtility.HtmlDecode(model.Leiras);
                model.UpdateBorviz(borviz, this.UnitOfWork);

                var errorList = this.UnitOfWork.SafeSave();

                if (errorList != null)
                {
                    foreach (var error in errorList)
                    {
                        this.ModelState.AddModelError(string.Empty, error);
                    }
                }
                else
                {
                    return RedirectToAction("Edit", new { id = model.Id });
                }
            }

            model.Init(this.UnitOfWork);
            return View(model);
        }

        #endregion

        #region Picture

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public ActionResult ManagePicture(int borvizId)
        {
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(borvizId);

            return View(new ManagePictureModel(borviz));
        }
        
        [HttpPost]
        public ActionResult PictureList(int borvizId)
        {
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(borvizId);

            return PartialView(new ManagePictureModel(borviz));
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult UploadPicture(int borvizId, HttpPostedFileBase file, string szerzo, string datum)
        {
            StringBuilder errorMessage = new StringBuilder();
            DateTime date;

            if (string.IsNullOrEmpty(szerzo)) errorMessage.AppendLine("Szerzo is required!");
            if (string.IsNullOrEmpty(datum)) errorMessage.AppendLine("Datum is required!");
            if (file == null || file.ContentLength == 0) errorMessage.AppendLine("File is required!");

            if (!DateTime.TryParse(datum, out date))
            {
                errorMessage.AppendLine("Datum nincs jo formatumban!");
            }

            if (errorMessage.Length == 0)
            {
                if (file != null && file.ContentLength > 0)
                {
                    string folder = Server.MapPath(string.Format("~/Kepek/{0}", borvizId));

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(folder, fileName);
                    file.SaveAs(path);

                    AddFenykep(borvizId, szerzo, string.Format("~/Kepek/{0}/{1}", borvizId, fileName), date);
                }
            }
            else
            {
                return Content(errorMessage.ToString());
            }

            return Content(string.Empty);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult DeleteFenykep(int borvizId, int fenykepId)
        {
            var fenykep = this.UnitOfWork.FenykepRepository.GetByID(fenykepId);
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(borvizId);

            if (fenykep != null)
            {
                if (System.IO.File.Exists(fenykep.File))
                {
                    System.IO.File.Delete(fenykep.File);
                }

                borviz.Fenykepek.Remove(fenykep);
                this.UnitOfWork.FenykepRepository.Delete(fenykep);

                this.UnitOfWork.Save();
            }

            return PartialView("PictureList", new ManagePictureModel(borviz));
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public void SetElsodleges(int borvizId, int fenykepId)
        {
            this.UnitOfWork.FenykepRepository.SetElsodleges(borvizId, fenykepId);
            this.UnitOfWork.Save();
        }
        
        private void AddFenykep(int borvizId, string szerzo, string path, DateTime datum)
        {
            Fenykep fenykep = new Fenykep() { Szerzo = szerzo, Datum = datum, File = path };
            Borviz borviz = this.UnitOfWork.BorvizRepository.GetByID(borvizId);

            borviz.Fenykepek.Add(fenykep);

            this.UnitOfWork.Save();
        }

        #endregion

        #region View all

        [HttpGet]
        public ActionResult ViewAll()
        {
            ViewAllModel model = new ViewAllModel(this.UnitOfWork);

            return View(model);
        }

        [HttpGet]
        public ActionResult Info(int id)
        {
            var borviz = this.UnitOfWork.BorvizRepository.GetByID(id);

            return PartialView(new BorvizSummaryModel(borviz, true));
        }

        #endregion

        #region Search

        [HttpGet]
        public ActionResult SearchPanel()
        {
            return PartialView(new SearchPanelModel(this.UnitOfWork));
        }

        [HttpPost]
        public JsonResult Search(DataTableModel param, SearchParamModel searchParam)
        {
            int total = 0;
            var borvizList = this.UnitOfWork.BorvizRepository.Search(out total, param, searchParam);

            var data = new
            {
                sEcho = param.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = borvizList
            };

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #endregion
    }
}
